#include "childwnd.h"
#include <QFileInfo>
#include<QFileDialog>
#include <QRegularExpression>

ChildWnd::ChildWnd()
{
    //子窗口关闭时销毁该类的实例对象
    setAttribute(Qt::WA_DeleteOnClose);
    m_bSaved = false;

}

void ChildWnd::newDoc()
{
    static int wndSegNum = 1 ;
    m_CurDocPath = QString("WPS 文档 %1")
                  .arg(wndSegNum++);

    setWindowTitle(m_CurDocPath  +"[*]" + "-MyWPS");
    connect(document(),SIGNAL(contentsChanged()),
            this,SLOT(docBeModified()));
}

QString ChildWnd::getcurDocName()
{
    return QFileInfo(m_CurDocPath).fileName();
}

bool ChildWnd::loadDoc(const QString &docName)
{
    if(!docName.isEmpty())
    {
        QFile file(docName);
        if(!file.exists()) return false;
        if(!file.open(QFile::ReadOnly))return false;
        QByteArray text = file.readAll();
        if(Qt::mightBeRichText(text))
        setHtml(text);
        else
        setPlainText(text);
        setCurDoc(docName);
        connect(document(),SIGNAL(contentschanged()),
        this,SLOT(docBeModified()));
        return true;
    }
}

void ChildWnd::setCurDoc(const QString &docName)
{
    m_CurDocPath = QFileInfo(docName).canonicalFilePath();
    m_bSaved = true;
    document()->setModified(false);//文档未改动
    setWindowModified(false);
    setWindowTitle(getcurDocName()+"[*]");

}



void ChildWnd::docBeModified()
{
     setWindowModified(document()->isModified());
}

bool ChildWnd::saveDoc()
{
    if (m_bSaved && !m_CurDocPath.isEmpty()) {
        // 如果文档已经保存过，直接保存到原路径
        return saveToFile(m_CurDocPath);
    } else {
        // 如果文档未保存过，调用另存为功能
        return saveAsDoc();
    }
}

bool ChildWnd::saveAsDoc()
{
    QString docName = QFileDialog::getSaveFileName(this,
                                                   "保存文档",
                                                   "",
                                                   "文本文件(*.txt);;HTML文件(*.html *.htm);;所有文件(*.*)");
    if (!docName.isEmpty()) {
        return saveToFile(docName);
    }
    return false;
}


bool ChildWnd::saveToFile(const QString &docName)
{
    QFile file(docName);
    if (!file.open(QFile::WriteOnly | QFile::Truncate)) {
        return false;
    }

    // 检查文档是否可能是 HTML 格式
    QString text = document()->toPlainText();
    QRegularExpression htmlTagRegex("<[^>]+>");
    bool isHtml = htmlTagRegex.match(text).hasMatch();

    if (isHtml) {
        file.write(document()->toHtml().toUtf8());
    } else {
        file.write(document()->toPlainText().toUtf8());
    }

    setCurDoc(docName);
    return true;
}
